package com.haha.helloworld.datastorage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.haha.helloworld.R;

public class SharedPreferencesActivity extends AppCompatActivity {
    private EditText et_name;
    private Button btn_save;
    private Button btn_show;
    private TextView tv_content;
    //SharedPreferences用来读取
    private SharedPreferences mySharedPreferences;
    //SharedPreferences.Editor用来写入
    private SharedPreferences.Editor myEditor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences);
        et_name=(EditText)findViewById(R.id.et_name);
        btn_save=(Button)findViewById(R.id.btn_save);
        btn_show=(Button)findViewById(R.id.btn_show);
        tv_content=(TextView)findViewById(R.id.tv_content);
        //存储的位置就是/data/data/应用的id(applicationid)/shared_prefs/mydata.xml
        //会生成一个xml文件,来存储键值对
        mySharedPreferences= getSharedPreferences("mydata", MODE_PRIVATE);
        myEditor=mySharedPreferences.edit();
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置键值对
                myEditor.putString("name",et_name.getText().toString());
                myEditor.commit();
            }
        });
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取出值
                tv_content.setText(mySharedPreferences.getString("name",""));

            }
        });
    }
}